package io.zhengsh.nio.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SelectorDemo {
    public static void main(String[] args) throws IOException {
        // 1. 获取 Selector 选择器
        Selector selector = Selector.open();

        // 2. 获取通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();

        // 3. 设置为非阻塞
        socketChannel.configureBlocking(false);

        // 4. 绑定连接
        socketChannel.bind(new InetSocketAddress(9999));

        // 5. 将通道注册到选择器
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);


        // 查询已经就绪的通道操作
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        Iterator<SelectionKey> iterator = selectedKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = iterator.next();

            // 判断 key 就绪状态操作
            if (key.isAcceptable()) {
                // a connection was accepted by a ServerSocketChannel.
            } else if (key.isConnectable()) {
                // a connection was established with a remote server.
            } else if (key.isReadable()) {
                // a channel is ready for reading
            } else if (key.isWritable()) {
                // a channel is ready for writing
            }
        }
        iterator.remove();
    }
}
